(function(window, angular) {
	'use strict';
	angular.module("Controller.Sales.SellBusiness", [])
	.controller("SellBusinessCtrl", ["$scope", "$state","ybWidget", "ybHttp", "UserContextService", "MESG_TYPE", "$timeout", "$filter", "EventBus", "$stateParams",
		function($scope, $state, ybWidget, ybHttp, UserContextService, MESG_TYPE, $timeout, $filter, EventBus, $stateParams) {
			$scope.activeFlag = [true, false, false];
			$scope.tabFlag = {};
			var tabFlag = {
				0: "新增",
				1: "编辑",
				2: "详情"
			};

			// 分页
			$scope.pageInfo = {
				totalPages: 1,
				totalRows: 0,
				pageSize: 10,
				curPage: 1
			};

			// 表格数据
			$scope.dataList = [];

			// 详情
			$scope.detailInfo = {}
			$scope.detailObj = {
				materialsList: [],
				traceLog: [],
				visitLog: []
			}
			
			$scope.markInfo = {
				allCheckedBill: false,
				allCheckedMaterial: false
			};
			$scope.dataList = [{
				businessId: 10000001
			}];

			$scope.condition = {}

			$scope.orderObj = {
				isDirectCast: 0,
				isImprove: 0
			};

			$scope.tableConfig = {
				fixedWidth: 150,
				scrollWidth: 1200,
				tableCol: [{
						type: "",
						name: "商机单号",
						dataField: "buCode",
						width: 180,
						isShow: true,
						isFixed: false,
						toSort: false,
						sortType: "",
						clickFn: "viewDetail"
					},
					{
						type: "",
						name: "商机状态",
						dataField: "buState",
						width: 150,
						isShow: true,
						isFixed: false,
						toSort: false,
						sortType: "",
					},
					{
						type: "",
						name: "产品组",
						dataField: "productGroup",
						width: 150,
						isShow: true,
						isFixed: false,
						toSort: false,
						sortType: "",
					},
					{
						type: "",
						name: "需求产品型号",
						dataField: "productType",
						width: 150,
						isShow: true,
						isFixed: false,
						toSort: false,
						sortType: "",
					},
					{
						type: "",
						name: "联系人",
						dataField: "linkman",
						width: 150,
						isShow: true,
						isFixed: false,
						toSort: false,
						sortType: "",
					},
					{
						type: "",
						name: "电话",
						dataField: "phone",
						width: 150,
						isShow: true,
						isFixed: false,
						toSort: false,
						sortType: "",
					},
					{
						type: "",
						name: "区域信息",
						dataField: "regionInfo",
						width: 150,
						isShow: true,
						isFixed: false,
						toSort: false,
						sortType: "",
					},
					{
						type: "",
						name: "crm单号",
						dataField: "crmOrder",
						width: 150,
						isShow: true,
						isFixed: false,
						toSort: false,
						sortType: "",
					},
					{
						type: "",
						name: "创建人",
						dataField: "createUserName",
						width: 150,
						isShow: true,
						isFixed: false,
						toSort: false,
						sortType: "",
					},
					{
						type: "",
						name: "创建日期",
						dataField: "createTimeShow",
						width: 150,
						isShow: true,
						isFixed: false,
						toSort: false,
						sortType: "",
					},
					{
						type: "operate",
						name: "操作",
						dataField: "",
						width: 150,
						isShow: true,
						isFixed: true,
						toSort: false,
						sortType: ""
					}
				]
			};

			$scope.changeTab = function(index) {
				$scope.activeFlag = [false, false, false];
				$scope.activeFlag[index] = true;
				$scope.submitted = false;
				switch (index) {
					case 0:
						initData();
						break;
					case 1:
						resetData();
						break;
					case 2:
						resetData();
						break;
					case 3:
						break;
					default:
						break;
				}
			};

			function initData() {
				$scope.tabFlag = {};
			}

			$scope.switchToolbar = function(toolbar) {
				if (!!$scope.toolbarConfig["show" + toolbar]) {
					$scope.toolbarConfig["show" + toolbar] = false;
				} else {
					$timeout(function() {
						$scope.toolbarConfig["show" + toolbar] = true;
					});
				}
			};

			$scope.selectRow = function(index) {
				$scope.markInfo.cueRow = index;
			};

			$scope.toSort = function(config, index) {
				ybWidget.ToSort(config, index);
			};

			$scope.setFixedWidth = function() {
				$scope.tbStyle = {
					scrollLeft: {
						left: $scope.tableConfig.fixedWidth + "px"
					}
				};
			};

			// 详情
			$scope.tdClick = function(item, fnType) {
				switch (fnType) {
					case "viewDetail":
						viewDetail(item);
						break;
					default:
						break;
				}
			};

			// 详情
			function viewDetail(item) {
				$scope.tabFlag.type = 1;
				$scope.tabFlag.name = tabFlag[2];
				getDetailInfo(item.id)
				$scope.changeTab(2);
			}

			// 获取详情
			function getDetailInfo(id) {
				var service = "device";
				var reqUrl = "/sellBusiness/item";
				var param = {};
				param.id = id
				ybHttp.Get(service, reqUrl, param).then(function (resp) {
					if (resp.code !== 0) {
						ybWidget.ShowMessage(resp, MESG_TYPE.Error);
						return;
					}
					$scope.detailInfo = resp.value;
					if ($scope.tabFlag.name == '编辑') {
						$scope.businessForms = $scope.detailInfo;
					}
				})
			}

			$scope.cancel = function() {
				$scope.changeTab(0);
			};

			$scope.switchDataPicker = function(index) {
				$scope.datePickerFlag = [false, false];
				if (angular.isDefined(index)) {
					$scope.datePickerFlag[index] = true;
				}
			};

			// 删除商机单
			$scope.removeBusiness = function() {
				var service = "device";
				var reqUrl = "/sellBusiness/delete";
				var ids = [];
				for (var i = 0, len = $scope.dataList.length; i < len; i++) {
					if (!!$scope.dataList[i].isChecked) {
						ids.push($scope.dataList[i].id);
					}
				}
			
				if (ids.length === 0) {
					ybWidget.ShowMessage('请选择需要删除的行');
					return;
				}
				ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function() {
					ybHttp.Post(service, reqUrl, ids).then(function (resp) {
						if (resp.code !== 0) {
							ybWidget.ShowMessage(resp, MESG_TYPE.Error);
							return;
						}
						ybWidget.ShowToaster('success', '操作成功');
						getDataList();
					})
				});
			}

			// 当前时间
			$scope.currentDate = "";

			// 获取商机管理列表
			function getDataList(curPage) {
				$scope.dataList = [];
				var service = "device";
				var reqUrl = "/sellBusiness/list";
				var param = {};
				param.pageSize = $scope.pageInfo.pageSize;
				if (!!curPage) {
					$scope.pageInfo.curPage = curPage;
				}
				param.pageNum = $scope.pageInfo.curPage;
				param.filters = $scope.condition;
				ybHttp.Post(service, reqUrl, param).then(function (resp) {
					if (resp.code !== 0) {
						ybWidget.ShowMessage(resp, MESG_TYPE.Error);
						return;
					}
					$scope.markInfo.allChecked = false;
					angular.forEach(resp.value.list, function (item) {
						item.isChecked = false;
						item.createTimeShow = $filter("YbDate")(item.createTime,'yyyy-MM-dd HH:mm:ss');
					});
					$scope.pageInfo.totalRows = resp.value.total;
					$scope.pageInfo.totalPages = resp.value.pages;
					$scope.dataList = resp.value.list;
				});
			}

			$scope.selectAll = function () {
				for (var i = 0; i < $scope.dataList.length; i++) {
						$scope.dataList[i].isChecked = $scope.markInfo.allChecked;
				}
				$scope.markInfo.crmCodeAll = false
				for (var i = 0; i < $scope.dataList.length; i++) {
						if ($scope.dataList[i].dealerLevelName) {
								$scope.markInfo.crmCodeAll = true
						}
				}
		};

			// 高级搜索
			$scope.toolbarConfig = {
				showAdvanceSearch: false,
				showColConfig: false
			};

			$scope.switchToolbar = function (toolbar) {

				if (!!$scope.toolbarConfig["show" + toolbar]) {
					$scope.toolbarConfig["show" + toolbar] = false;
				} else {
					$timeout(function () {
						$scope.toolbarConfig["show" + toolbar] = true;
					});
				}
			};

			// 高级搜索重置
			$scope.reset = function () {
				$scope.condition = {};
			};

			// 分页跳转
			$scope.search = function (curpage) {
				getDataList(curpage);
			};

			// 格式化日期
			Date.prototype.Format = function (fmt) {
				var o = {
						"M+": this.getMonth() + 1, //月份 
						"d+": this.getDate(), //日 
						"H+": this.getHours(), //小时 
						"m+": this.getMinutes(), //分 
						"s+": this.getSeconds(), //秒 
						"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
						"S": this.getMilliseconds() //毫秒 
				};
				if (/(y+)/.test(fmt)){
					fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
				} 
				for (var k in o){
					if (new RegExp("(" + k + ")").test(fmt)) {
						fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
					}
				}
				return fmt;
			}

			// 跳转清空
			function resetData () {
				$scope.businessForms = {}
				$scope.orderObj.materialsList = []
			};

			$scope.businessForms = {
				buState: '0'
			}

			// 跳转新增页
			$scope.addBusiness = function() {
				$scope.currentDate = new Date().Format("yyyy-MM-dd");
				$scope.tabFlag.name = tabFlag[0];
				$scope.changeTab(1);
			};

			// 跳转编辑页
			$scope.editBusiness = function(item) {
				$scope.tabFlag.name = tabFlag[1];
				$scope.changeTab(1);
				getDetailInfo(item.id);
			};

			// 新增/编辑 商机单
			$scope.addBusinessForm = function(item) {
				var service = "device";
				var reqUrl = "/sellBusiness/add";
				var param = angular.copy($scope.businessForms);
				if ($scope.tabFlag.name == '编辑') {
					reqUrl = "/sellBusiness/update";
				}
				ybHttp.Post(service, reqUrl, param).then(function (resp) {
					if (resp.code !== 0) {
						ybWidget.ShowMessage(resp, MESG_TYPE.Error);
						return;
					}
					ybWidget.ShowToaster('success', '操作成功');
					$scope.changeTab(0);
					getDataList(1);
				});
				
			};

			// 丢单/赢单
			$scope.lostWin = function(item,state) {
				var service = "device";
				var reqUrl = "/sellBusiness/updateState";
				var param = {
					id : item.id,
					buState : state
				};
				ybHttp.Post(service, reqUrl, param).then(function (resp) {
					if (resp.code !== 0) {
						ybWidget.ShowMessage(resp, MESG_TYPE.Error);
						return;
					}
					ybWidget.ShowToaster('success', '操作成功');
					$scope.changeTab(0);
					getDataList(1);
				});
				
			};

			(function() {
				$scope.setFixedWidth();
				getDataList();
			})();
		}
	]);
})(window, window.angular);
